import { IStringUtils } from '@/utils/interface/IStringUtils';

class StringUtils implements IStringUtils {
  async asyncReplaceAll(
    str: string,
    regexp: string | RegExp,
    asyncFn: string | Function
  ): Promise<string> {
    if (typeof asyncFn === 'string') return str.replaceAll(regexp, asyncFn);
    if (typeof asyncFn !== 'function')
      throw new Error('asyncFn is not a function');

    let reg;
    if (typeof regexp === 'string')
      // 字符串转正则的通用代码
      reg = new RegExp(regexp.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g');
    else {
      if (!regexp.global) {
        throw new Error('regexp is not global');
      }
      reg = new RegExp(regexp);
    }

    let result = [];
    let match;
    let lastIndex = 0; // 上一次匹配的结束位置

    while ((match = reg.exec(str)) !== null) {
      const item = asyncFn(match[0]);
      const preFix = str.slice(lastIndex, match.index);
      lastIndex = match.index + match[0].length;
      result.push(preFix);
      result.push(item);
    }
    result.push(str.slice(lastIndex));

    result = await Promise.all(result);

    return result.join('');
  }
}

const stringUtils = new StringUtils();
export default stringUtils;
